<?php

namespace app\index\controller;

use classes\RedisClass;
use classes\TokenBucket;
use service\LogService;
use think\Controller;
use think\Db;
use think\facade\Cache;
use think\Queue;
use think\facade\Env;
use service\WechatService;

class Ticket extends Controller
{


    public function __construct()
    {

        parent::__construct();

//        if (!Env::get('app_debug') && !isMobile()) {
//            tip_alert('请在微信手机端访问！');
//        }

        if (Env::get('app_debug')) {
            session('wxd_openid', 'o6rBgxER1najTK-KGVmQSa9iPZig');
        }

    }

    function auth($url = '')
    {

        if (!empty($url)) {
            session('callback_url', $url);
        }
        if (isset($_GET['code']) && !empty($_GET['code'])) {
            $appid = sysconf('wechat_appid');
            $appsecret = sysconf('wechat_appsecret');
            $code = $_GET['code'];
            $weixinurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $appsecret . "&code=" . $code . "&grant_type=authorization_code ";
            //获取openid
            $res = curl($weixinurl);
            $token = json_decode($res, true);

            if (isset($token['openid'])) {
                $openid = $token['openid'];
                session("wxd_openid", $openid);
                $callback_url = session('callback_url');
                header("Location:$callback_url");
                exit(0);

            }
        } else {
            if (Env::get('app_debug')) {
                $this->redirect('http://sy.zoudingyong.com/codetoany/getcode.php?auk=tickettest');
            } else {
                $this->redirect('http://sy.zoudingyong.com/codetoany/getcode.php?auk=ticket');
            }

        }


    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {

        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }
        $config = RedisClass::get_vote_config_info();
        $banner = RedisClass::get_banner_info();
        $city = Db::name('tp_region')
            ->field('id city_id,name')
            ->where('parent_id', 18)
            ->order('sort desc')
            ->cache(0)
            ->select();
        //分享朋友圈
        $current_url = $this->request->url(true);
        try {
            $wx_config = [
                'appid' => sysconf('wechat_appid'),
                'appsecret' => sysconf('wechat_appsecret'),
            ];
            $wechat = \WeChat\Script::instance($wx_config);
            $signPackage = $wechat->getJsSign($current_url);
        } catch (\Exception $e) {
            $signPackage = [
                'appId' => sysconf('wechat_appid'),
                'timestamp' => '',
                'nonceStr' => '',
                'signature' => '',
            ];
        };

        return $this->fetch('index', [
            'city' => $city,
            'banner' => $banner,
            'config' => $config,
            'current_url' => $current_url,
            'signPackage' => $signPackage,
        ]);
    }

    /**
     * 活动指南
     * @return mixed
     */
    public function zhinan()
    {

        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }
        $config = RedisClass::get_vote_config_info();
        $banner = RedisClass::get_banner_info();
        $city = Db::name('tp_region')
            ->field('id city_id,name')
            ->where('parent_id', 18)
            ->order('sort desc')
            ->cache(0)
            ->select();
        //分享朋友圈
        $current_url = $this->request->url(true);
        try {
            $wx_config = [
                'appid' => sysconf('wechat_appid'),
                'appsecret' => sysconf('wechat_appsecret'),
            ];
            $wechat = \WeChat\Script::instance($wx_config);
            $signPackage = $wechat->getJsSign($current_url);
        } catch (\Exception $e) {
            $signPackage = [
                'appId' => sysconf('wechat_appid'),
                'timestamp' => '',
                'nonceStr' => '',
                'signature' => '',
            ];
        };

        return $this->fetch('zhinan', [
            'city' => $city,
            'banner' => $banner,
            'config' => $config,
            'current_url' => $current_url,
            'signPackage' => $signPackage,
        ]);
    }

    /**
     * 视频集锦
     * @return mixed
     */
    public function video()
    {

        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }
        $config = RedisClass::get_vote_config_info();
        $banner = RedisClass::get_banner_info();
        $article = Db::name('tp_article')
            ->where('cate_id', 2)
            ->order('sort desc,article_id desc ')
            ->select();
        //分享朋友圈
        $current_url = $this->request->url(true);
        try {
            $wx_config = [
                'appid' => sysconf('wechat_appid'),
                'appsecret' => sysconf('wechat_appsecret'),
            ];
            $wechat = \WeChat\Script::instance($wx_config);
            $signPackage = $wechat->getJsSign($current_url);
        } catch (\Exception $e) {
            $signPackage = [
                'appId' => sysconf('wechat_appid'),
                'timestamp' => '',
                'nonceStr' => '',
                'signature' => '',
            ];
        };

        return $this->fetch('video', [
            'article' => $article,
            'banner' => $banner,
            'config' => $config,
            'current_url' => $current_url,
            'signPackage' => $signPackage,
        ]);
    }

    /**
     * 活动动态
     * @return mixed
     */
    public function dongtai()
    {

        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }
        $config = RedisClass::get_vote_config_info();
        $banner = RedisClass::get_banner_info();
        $article = Db::name('tp_article')
            ->where('cate_id', 1)
            ->order('sort desc,article_id desc ')
            ->select();
        //分享朋友圈
        $current_url = $this->request->url(true);
        try {
            $wx_config = [
                'appid' => sysconf('wechat_appid'),
                'appsecret' => sysconf('wechat_appsecret'),
            ];
            $wechat = \WeChat\Script::instance($wx_config);
            $signPackage = $wechat->getJsSign($current_url);
        } catch (\Exception $e) {
            $signPackage = [
                'appId' => sysconf('wechat_appid'),
                'timestamp' => '',
                'nonceStr' => '',
                'signature' => '',
            ];
        };

        return $this->fetch('dongtai', [
            'article' => $article,
            'banner' => $banner,
            'config' => $config,
            'current_url' => $current_url,
            'signPackage' => $signPackage,
        ]);
    }

    /**
     * 门票
     * @return mixed
     */
    public function menpiao()
    {

        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }
        $config = RedisClass::get_vote_config_info();
        $banner = RedisClass::get_banner_info();
        $city = Db::name('tp_region')
            ->field('id city_id,name')
            ->where('parent_id', 18)
            ->order('sort desc')
            ->cache(0)
            ->select();
        //分享朋友圈
        $current_url = $this->request->url(true);
        try {
            $wx_config = [
                'appid' => sysconf('wechat_appid'),
                'appsecret' => sysconf('wechat_appsecret'),
            ];
            $wechat = \WeChat\Script::instance($wx_config);
            $signPackage = $wechat->getJsSign($current_url);
        } catch (\Exception $e) {
            $signPackage = [
                'appId' => sysconf('wechat_appid'),
                'timestamp' => '',
                'nonceStr' => '',
                'signature' => '',
            ];
        };

        return $this->fetch('menpiao', [
            'city' => $city,
            'banner' => $banner,
            'config' => $config,
            'current_url' => $current_url,
            'signPackage' => $signPackage,
        ]);
    }


    /**
     * 报名
     * @return mixed
     */
    public function reg()
    {

        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }
        $config = RedisClass::get_vote_config_info();
        $banner = RedisClass::get_banner_info();

        if (request()->isPost()) {

            $info = $this->request->post();
            if (empty($info['name'])
                || empty($info['mobile'])
                || empty($info['cardid'])
                || empty($info['address'])
            ) {
                return json(['code' => 1, 'message' => '信息填写不完整']);
            }

            if ($info['cate_id'] == 1) {
                //开幕式开始时间10.31 0.0.0
//                if (time() < 1698681600) {
//                    return json(['code' => 1, 'message' => '开幕式门票10.31开放预约']);
//                }
                //开幕式截止11.7 16.00.00
                if (time() > 1699344000) {
                    return json(['code' => 1, 'message' => '开幕式门票预约已结束']);
                }
            }

            if ($info['cate_id'] == 2) {

                //音乐节开始时间11.1 0.0.0
//                if (time() < 1698768000) {
//                    return json(['code' => 1, 'message' => '音乐节门票11.1开放预约']);
//                }

                //音乐节截止11.7 23.59.59
//                if (time() > 1699372799) {
                    return json(['code' => 1, 'message' => '音乐节门票预约已结束']);
//                }
            }
            return json(['code' => 1, 'message' => '门票预约已结束']);

            Db::name('tp_vote_item')->insertGetId([
                'cate_id' => $info['cate_id'] ?: '',
                'wechat_id' => $wecha_id,
                'item' => $info['name'] ?: '',
                'sub_item' => $info['name'] ?: '',
                'phone' => $info['mobile'] ?: '',
                'info' => $info['cardid'] ?: '',
                'info2' => build_coupon(16),
                'address' => $info['address'] ?: '',
                'addtime' => time(),
            ]);

            return json(['code' => 0, 'message' => '预约成功']);

        } else {

            $info = $this->request->get();

            $myreg = Db::name('tp_vote_item')
                ->where('wechat_id', $wecha_id)
                ->where('cate_id', $info['cate_id'])
                ->find();

            if ($myreg) {
                $this->redirect("/index/ticket/myticket?cate_id={$info['cate_id']}");
            }

            //分享朋友圈
            $current_url = $this->request->url(true);
            try {
                $wx_config = [
                    'appid' => sysconf('wechat_appid'),
                    'appsecret' => sysconf('wechat_appsecret'),
                ];
                $wechat = \WeChat\Script::instance($wx_config);
                $signPackage = $wechat->getJsSign($current_url);
            } catch (\Exception $e) {
                $signPackage = [
                    'appId' => sysconf('wechat_appid'),
                    'timestamp' => '',
                    'nonceStr' => '',
                    'signature' => '',
                ];
            };

            return $this->fetch('reg', [
                'banner' => $banner,
                'cate_id' => $info['cate_id'],
                'config' => $config,
                'current_url' => $current_url,
                'signPackage' => $signPackage,
            ]);

        }
    }

    /**
     * 报名
     * @return mixed
     */
    public function reg3()
    {

        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }
        $config = RedisClass::get_vote_config_info();
        $banner = RedisClass::get_banner_info();

        if (request()->isPost()) {

            $info = $this->request->post();
            if (empty($info['name'])
                || empty($info['mobile'])
                || empty($info['sex'])
                || empty($info['intro'])
                || empty($info['address'])
            ) {
                return json(['code' => 1, 'message' => '信息填写不完整']);
            }

            if ($info['cate_id'] == 3) {
                //开幕式开始时间10.31 0.0.0
//                if (time() < 1698681600) {
//                    return json(['code' => 1, 'message' => '盘龙河七彩公益健康跑10.31开放报名']);
//                }
                //公益健康跑截止11.6 17.30
                if (time() > 1699263000) {
                    return json(['code' => 1, 'message' => '公益健康跑报名已结束']);
                }
            }
            return json(['code' => 1, 'message' => '公益健康跑报名已结束']);

            Db::name('tp_vote_item')->insertGetId([
                'cate_id' => $info['cate_id'] ?: '',
                'wechat_id' => $wecha_id,
                'item' => $info['name'] ?: '',
                'sub_item' => $info['name'] ?: '',
                'phone' => $info['mobile'] ?: '',
                'info2' => build_coupon(16),
                'address' => $info['address'] ?: '',
                'sex' => $info['sex'] ?: '',
                'intro' => $info['intro'] ?: '',
                'addtime' => time(),
            ]);

            return json(['code' => 0, 'message' => '报名成功']);

        } else {

            $info = $this->request->get();

            $myreg = Db::name('tp_vote_item')
                ->where('wechat_id', $wecha_id)
                ->where('cate_id', $info['cate_id'])
                ->find();

            if ($myreg) {
                $this->redirect("/index/ticket/myticket?cate_id={$info['cate_id']}");
            }

            //分享朋友圈
            $current_url = $this->request->url(true);
            try {
                $wx_config = [
                    'appid' => sysconf('wechat_appid'),
                    'appsecret' => sysconf('wechat_appsecret'),
                ];
                $wechat = \WeChat\Script::instance($wx_config);
                $signPackage = $wechat->getJsSign($current_url);
            } catch (\Exception $e) {
                $signPackage = [
                    'appId' => sysconf('wechat_appid'),
                    'timestamp' => '',
                    'nonceStr' => '',
                    'signature' => '',
                ];
            };

            return $this->fetch('reg3', [
                'banner' => $banner,
                'cate_id' => $info['cate_id'],
                'config' => $config,
                'current_url' => $current_url,
                'signPackage' => $signPackage,
            ]);

        }
    }

    /**
     * 我的票
     * @return mixed
     */
    public function myticket()
    {

        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }
        $info = $this->request->get();
        $config = RedisClass::get_vote_config_info();
        $banner = RedisClass::get_banner_info();
        $myreg = Db::name('tp_vote_item')
            ->where('wechat_id', $wecha_id)
            ->where('cate_id', $info['cate_id'])
            ->find();

        if (empty($myreg)) {
            $this->redirect("/index/ticket/reg?cate_id={$info['cate_id']}");
        }
        //分享朋友圈
        $current_url = $this->request->url(true);
        try {
            $wx_config = [
                'appid' => sysconf('wechat_appid'),
                'appsecret' => sysconf('wechat_appsecret'),
            ];
            $wechat = \WeChat\Script::instance($wx_config);
            $signPackage = $wechat->getJsSign($current_url);
        } catch (\Exception $e) {
            $signPackage = [
                'appId' => sysconf('wechat_appid'),
                'timestamp' => '',
                'nonceStr' => '',
                'signature' => '',
            ];
        };

        return $this->fetch('myticket', [
            'banner' => $banner,
            'config' => $config,
            'myreg' => $myreg,
            'current_url' => $current_url,
            'signPackage' => $signPackage,
        ]);
    }


    /**
     * 核销
     * @return mixed
     */
    public function hexiao()
    {

        $wxd_openid = session("wxd_openid");
        if (!$wxd_openid) {
            $this->auth($this->request->url(true));
        }

        //如果未登录
//        if (!session('partner_id')) {
//            $this->redirect('/index/partner/login');
//        }

        $config = RedisClass::get_vote_config_info();
        if (request()->isPost()) {

            $code = input('code');

            $record = Db::name('tp_vote_item')->where('info2', $code)->find();
            if (!$record) {
                return json(['code' => 1, 'message' => '无效核销码!']);
            }

//            if ($record['partner_id'] != session('partner_id')) {
//                return json(['code' => 1, 'message' => ' 非本店领取的券无法核销!']);
//            }

            if ($record['status'] == 1) {
                return json(['code' => 1, 'message' => '该码已经被核销了!']);
            }

            $data['status'] = 1;
            $data['updatetime'] = time();

            if ($result = Db::name('tp_vote_item')->where('info2', $code)->update($data)) {
                return json(['code' => 0, 'message' => '核销成功！']);
            } else {
                return json(['code' => 1, 'message' => '核销失败,请重新扫码!']);
            }

        } else {
            $info = $this->request->get();

            //分享朋友圈
            $current_url = $this->request->url(true);
            try {
                $wx_config = [
                    'appid' => sysconf('wechat_appid'),
                    'appsecret' => sysconf('wechat_appsecret'),
                ];
                $wechat = \WeChat\Script::instance($wx_config);
                $signPackage = $wechat->getJsSign($current_url);
            } catch (\Exception $e) {
                $signPackage = [
                    'appId' => sysconf('wechat_appid'),
                    'timestamp' => '',
                    'nonceStr' => '',
                    'signature' => '',
                ];
            };

            return $this->fetch('hexiao', [
                'config' => $config,
                'current_url' => $current_url,
                'signPackage' => $signPackage,
            ]);
        }

    }

    /**
     * 详情页
     * @return mixed
     */
    public function detail()
    {

        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }

        $city = Db::name('tp_region')
            ->field('id city_id,name')
            ->where('parent_id', 18)
            ->order('sort desc')
            ->cache(0)
            ->select();

        //分享朋友圈
        $current_url = $this->request->url(true);
        try {
            $wx_config = [
                'appid' => sysconf('wechat_appid'),
                'appsecret' => sysconf('wechat_appsecret'),
            ];
            $wechat = \WeChat\Script::instance($wx_config);
            $signPackage = $wechat->getJsSign($current_url);
        } catch (\Exception $e) {
            $signPackage = [
                'appId' => sysconf('wechat_appid'),
                'timestamp' => '',
                'nonceStr' => '',
                'signature' => '',
            ];
        };

        return $this->fetch('detail', [
            'city' => $city,
            'current_url' => $current_url,
            'signPackage' => $signPackage,
        ]);
    }

}
